package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuMapper;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.*;

@Service
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    MenuMapper menuMapper;

    @Autowired
    RoleDao roleMapper;

    @Autowired
    UserDao sysUserMapper;
    @Autowired
    JedisPool jedisPool;


    @Override
    public List<Menu> getMenu(String username) {
        List<Menu> menuList =new ArrayList<>();
        //先在redis中查询，根据用户名
//        String jsons = jedisPool.getResource().get(username);
//        if (jsons !=null){
//            menuList = JSON.parseArray(jsons, Menu.class);
//            return menuList;
//        }

        //根据用户名username得到用户的id
        SysUser bySysUserName = sysUserMapper.findByUsername(username);
        //根据用户的id查询用户对应的角色列表
        Set<Role> roleSet = roleMapper.findRolesByUserId(bySysUserName.getId());

        Set<Menu> oneMenuSet =new HashSet<>();
        //遍历角色列表
        for (Role role : roleSet) {
            //根据角色列表查询对应的1级菜单集合  菜单等级 1   权限id
            Set<Menu> oneMenu = menuMapper.findMenuOfLevelOne(role.getId());
            //存入到以及菜单的总集和
            oneMenuSet.addAll(oneMenu);
        }
//        System.out.println(oneMenuSet);
        for (Menu menu : oneMenuSet) {
            for (Role role : roleSet) {
                List<Menu> twoMenuSet = menuMapper.findMenuByRoleIdAndParentId(role.getId(),menu.getId());
                menu.setChildren(twoMenuSet);
                menuList.add(menu);
            }
        }
        //排序 menuList
        Collections.sort(menuList, new Comparator<Menu>() {
            @Override
            public int compare(Menu o1, Menu o2) {
                //第二个参数 - 第一个参数: 降序
                return o2.getPriority()-o1.getPriority();
            }
        });

//        System.out.println(menuList);
//        String jsonString = JSON.toJSONString(menuList);
//        System.out.println(jsonString);
//        jedisPool.getResource().set(username,jsonString);

        return menuList;
    }

    /**
     * 查询所有的以继菜单
     * @return
     */
    @Override
    public List<Menu> getAllOnemenu() {
        List<Menu> list = menuMapper.getAllOnemenu();
        return list;
    }

    /**
     * 添加菜单的页面
     * @param menu
     */
    @Override
    public void add(Menu menu) {
        Integer level = menu.getLevel();
        //判断将要添加菜单的等级
        //如果是一级菜单，则修改path为最新数字
        if (level == 1){
            String oldmaxpath = menuMapper.findMaxOnePath();
            menu.setPath(Integer.parseInt(oldmaxpath) + 1+"");
            menu.setPriority(Integer.parseInt(oldmaxpath));
        }else{
            Integer maxTwoPriority = menuMapper.findMaxTwoPath(menu.getParentMenuId());
            if (maxTwoPriority == null){
                maxTwoPriority = 0;
            }
            String paraPath = menuMapper.findParaMenuPath(menu.getParentMenuId());
            menu.setPriority(maxTwoPriority+1);
            menu.setPath("/"+paraPath+"-"+menu.getPriority());
        }

        menuMapper.add(menu);
    }
    @Override
    public void edit(Menu menu) {
        Integer level = menu.getLevel();
        if (level == 1){
            String oldmaxpath = menuMapper.findMaxOnePath();
            menu.setPath(Integer.parseInt(oldmaxpath) + 1+"");
            menu.setPriority(Integer.parseInt(oldmaxpath));
        }else{
            Integer maxTwoPriority = menuMapper.findMaxTwoPath(menu.getParentMenuId());
            if (maxTwoPriority == null){
                maxTwoPriority = 1;
            }
            String paraPath = menuMapper.findParaMenuPath(menu.getParentMenuId());
            menu.setPriority(maxTwoPriority+1);
            menu.setPath("/"+paraPath+"-"+menu.getPriority());
        }
        menuMapper.edit(menu);
    }

    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //1.开始分页
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //2. 根据条件查询
        Page<Menu> page = menuMapper.findByCondition(queryPageBean.getQueryString());
        //3. 创建PageResult
        PageResult pageResult = new PageResult(page.getTotal(),page);
        return pageResult;
    }

    /**
     * 根据id进行查询
     * @param id
     * @return
     */
    @Override
    public Menu findById(Integer id) {
        return menuMapper.findById(id);
    }

    @Override
    public void delById(Integer id) {
        long count = menuMapper.findCountById(id);
        long mcount = menuMapper.findTwoMenu(id);

        if(count > 0 ) {
            //说明被关联
            throw new RuntimeException("该菜单被关联，不能删除！！");
        }else if(mcount > 0){
            throw new RuntimeException("该菜单存在子菜单，不能删除！！");
        }
        else {
            menuMapper.delById(id);
        }
    }


    @Override
    public List<Menu> findAll() {
        return menuMapper.findAll();
    }

    @Override
    public Integer[] find_role_menu(Integer id) {
        return menuMapper.find_role_menu(id);
    }
}
